package com.orhon.smartcampus.modules.base.mutation;

import com.alibaba.fastjson.JSON;
import com.orhon.smartcampus.basicComponents.Result;
import com.orhon.smartcampus.modules.base.dao.GradesDao;
import com.orhon.smartcampus.modules.base.dao.PeriodsDao;
import com.orhon.smartcampus.modules.base.entity.Grades;
import com.orhon.smartcampus.modules.base.entity.Periods;
import com.orhon.smartcampus.modules.base.gqlInputModel.GQLGradesInput;
import com.orhon.smartcampus.modules.base.inputMapper.GradesInputMapper;
import graphql.schema.DataFetcher;
import graphql.schema.DataFetchingEnvironment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
public class AddGradeMutation implements DataFetcher {


    @Autowired
    GradesDao gradesDao;

    @Autowired
    PeriodsDao periodsDao;

    /**
     * 新增/修改年级信息
     * editor : ths
     */
    @Override
    public Object get(DataFetchingEnvironment environment) throws Exception {

        GQLGradesInput input = GradesInputMapper.MAPPER.mapInput(environment.getArgument("inputData"));

        Grades grades = null;

        if (input.getId() != null) {
            grades = gradesDao.get(Grades.class, input.getId());
            grades.setUpdatedAt(new Date());
        } else {
            grades = new Grades();
            grades.setCreatedAt(new Date());
        }
        if(input.getSlug() != null ){

            grades.setGradeSlug(input.getSlug());
        }
        if(input.getNumber() != null){
            grades.setGradeNumber(input.getNumber());
        }
        if(input.getOrder() != null){
            grades.setGradeOrder(input.getOrder());
        }
        if(input.getMark() != null){

            grades.setMark(input.getMark());
        }
        if(input.getName() != null){
            grades.setGradeName(JSON.toJSONString(input.getName()));
        }
        if (input.getPeriod() != null) {
            Periods periods = periodsDao.get(Periods.class, input.getPeriod());
            grades.setPeriods(periods);
        }
        try {
            gradesDao.saveOrUpdate(grades);
        } catch (Exception e) {
            return Result.error(500, "" + e);
        }

        return Result.ok();
    }

}

